<template>
	<view class="container">
		<u-empty mode="list" icon="../../static/listEmpty.png" v-if="examList.length==0">
		</u-empty>
		<template v-else>
			<view class="main_content" @touchstart="touchStart" @touchend="touchEnd">
				<view class="layout-between questTypeContent">
					<view class="questionType">{{questionType}}题</view>
					<view class="questionAmount">
						<view>
							<text class="activeClr">{{currentNum}}</text>/{{total}}<!-- examList.length -->
						</view>
					</view>
				</view>
				<view class="questionContent">
					<view class="questionTitle">
						<view v-html="currentQuestion.stem"></view>
					</view>
					<view class="answer_item" v-if="currentQuestion.type == 1">
						<u-radio-group v-model="userAnswer.answer" placement="column" @change="groupChange"
							:labelSize="30" inactiveColor="#000" activeColor="#3888FF"
							:disabled="currentQuestion.isShowAnswer">
							<u-radio :customStyle="{padding: '12px'}" v-for="(item, index) in currentQuestion.options"
								:key="index" :label="item.label" :name="item.value" :style="[getBackgroundColor(item)]"
								v-if="currentQuestion.isShowAnswer">
							</u-radio>
							<u-radio :customStyle="{padding: '12px'}" v-for="(item, index) in currentQuestion.options"
								:key="index" :label="item.label" :name="item.value"
								v-if="!currentQuestion.isShowAnswer">
							</u-radio>
						</u-radio-group>
					</view>
					<template v-else-if="currentQuestion.type == 3">
						<u-radio-group v-model="userAnswer.answer" placement="column" @change="groupChange"
							:labelSize="30" inactiveColor="#000" activeColor="#3888FF"
							:disabled="currentQuestion.isShowAnswer" v-if="currentQuestion.isShowAnswer">
							<u-radio name="1" label="正确" :customStyle="{padding: '12px'}"
								:style="[getBackgroundColor(1)]"></u-radio>
							<u-radio name="0" label="错误" :customStyle="{padding: '12px'}"
								:style="[getBackgroundColor(0)]"></u-radio>
						</u-radio-group>
						<u-radio-group v-model="userAnswer.answer" placement="column" @change="groupChange"
							:labelSize="30" inactiveColor="#000" activeColor="#3888FF"
							:disabled="currentQuestion.isShowAnswer" v-if="!currentQuestion.isShowAnswer">
							<u-radio name="1" label="正确" :customStyle="{padding: '12px'}"></u-radio>
							<u-radio name="0" label="错误" :customStyle="{padding: '12px'}"></u-radio>
						</u-radio-group>
					</template>
					<template v-else-if="currentQuestion.type == 2">
						<u-checkbox-group v-model="userAnswer.answer" placement="column" @change="checkboxChange"
							:disabled="currentQuestion.isShowAnswer">
							<u-checkbox :customStyle="{padding: '8px'}" v-for="(item, index) in currentQuestion.options"
								:key="index" :label="item.label" :name="item.value">
							</u-checkbox>
						</u-checkbox-group>
					</template>
					<view class="determineBtn" v-if="!currentQuestion.isShowAnswer">
						<u-button text="确定" color="linear-gradient(to right, #7774ff, #017ffd,#01b1fd)"
							@click="onDetermine(currentQuestion)" class="itemBtn"></u-button>
					</view>
					<view class="answerResult" v-if="currentQuestion.isShowAnswer">
						<view class="layout-start">
							<view class="answerIcon">
								<u-icon name="checkmark-circle-fill" color="green" size="26"
									v-if="isRightAnswer"></u-icon>
								<u-icon name="close-circle-fill" color="red" size="26"
									v-if="!isRightAnswer && isRightAnswer!=null"></u-icon>
							</view>
							<view>{{resultText}}</view>
						</view>
						<view class="answers">
							<u-row>
								<u-col span="6">
									<view class="answerTxt">正确答案 </view>
									<view>
										<!-- {{currentQuestion.correctOptions}} -->
										{{outputList(currentQuestion.correctOptions) == 1 ? '正确' : outputList(currentQuestion.correctOptions) == 0 ? '错误' : outputList(currentQuestion.correctOptions)}}
									</view>
								</u-col>
								<u-col span="6" v-if="true">
									<view class="answerTxt">您的答案 </view>
									<view>
										<!-- {{currentQuestion.stuAnswer}} -->
										{{outputList(currentQuestion.stuAnswer) == 1 ? 'A' : outputList(currentQuestion.stuAnswer) == 0 ? 'B' : outputList(currentQuestion.stuAnswer)}}
									</view>
								</u-col>
							</u-row>
						</view>
					</view>
				</view>
			</view>
			<view class="analysis" v-if="currentQuestion.isShowAnswer">
				<view class="analysisTitle">
					答案解析
				</view>
				<view class="analysisContent">
					{{currentQuestion.analysis}}
				</view>
			</view>
			<view class="delItem">
				<u-button text="清空错题" color="linear-gradient(to right, #7774ff, #017ffd,#01b1fd)" @click="delWrongAll()"
					class="delBtn"></u-button>
			</view>
			<view class="bottom_area">
				<u-row>
					<!-- <u-col span="3">
					<view class="layout-column-center collection" @click="onCollect">
						<u-icon :name="collectIds.includes(currentQuestion.id) ? 'star-fill' :'star'" color="#FEB946"
							size="28"></u-icon>
						<view>收藏</view>
					</view>
				</u-col> -->
					<u-col span="4">
						<view class="answerSheet" @click="preNextClick(-1)">
							<image src="../../static/previous.png"></image>
							<view>上一题</view>
						</view>
					</u-col>
					<u-col span="4">
						<view class="answerSheet" @click="preNextClick(1)">
							<image src="../../static/next.png"></image>
							<view>下一题</view>
						</view>
					</u-col>
					<u-col span="4">
						<view class="answerSheet" @click="onAnswerSheet">
							<image src="../../static/answerSheet.png"></image>
							<view>题目</view>
						</view>
					</u-col>
				</u-row>
			</view>
		</template>
		<u-popup :show="showAnswerSheet" mode="bottom" @close="closeAnswer" @open="openAnswer">
			<view class="answerPanel">
				<view class="layout-between">
					<view class="card_title">题号</view>
					<view>
						<text class="titleTxt">
							未做
							<i class="titleText"></i>
						</text>
						<text class="titleTxt">
							答对
							<i class="titleText titleRight"></i>
						</text>
						<text class="titleTxt">
							答错
							<i class="titleText titleError"></i>
						</text>
					</view>
				</view>
				<view class="card_content">
					<view v-for="(item,index) in examList" :key="index" @click="onAnswerPanel(index)" :class="{'picker-item':true,
						error:!answerEqual(item.stuAnswer,item.correctOptions,item.type) && item.stuAnswer.length>0,
						right:answerEqual(item.stuAnswer,item.correctOptions,item.type) && item.stuAnswer.length>0}">
						{{index+1}}
					</view>
				</view>
			</view>
		</u-popup>
	</view>
</template>

<script>
	const _ = require("lodash")
	import {
		wrongMain,
		collectionAdd,
		collectionDelete,
		topicCollectionList,
		delWrong,
		delWrongAll
	} from "../../utils/api.js"
	export default {
		data() {
			return {
				examList: [],
				currentNum: 1,
				userAnswer: [{
					answer: [''],
					questionId: ''
				}],
				showAnswerSheet: false,
				statusIcon: '',
				isRightAnswer: null,
				resultText: null,
				collectIds: [],
				total: null, //总条数
				page: 1, //当前页码
				pageSize: 10, //每页显示数量
				userId: null,
			}
		},
		onLoad() {
			this.userId = uni.getStorageSync('userinfo').id
			this.getWrongList()
			this.getCollectionList()
		},
		methods: {
			onCollect() {
				// 如果获取的收藏列表中包含点击的题目id，就取消收藏
				if (this.collectIds.includes(this.currentQuestion.id)) {
					collectionDelete({
						id: this.currentQuestion.id
					}).then(s => {
						if (s.code === 20000) {
							console.log('取消收藏', s);
							// this.getCollectionList();
							let newCollectIds = this.collectIds.filter(item => !this.collectIds.includes(this
								.currentQuestion.id))
							this.collectIds = newCollectIds
							uni.showToast({
								title: '取消收藏',
								icon: 'none',
								duration: 1500
							});
							this.$forceUpdate()
						} else {
							uni.showToast({
								title: s.message,
								icon: 'none'
							})
						}
					})
				} else {
					// 否则添加收藏
					collectionAdd({
						userId: this.userId,
						questionId: this.currentQuestion.id
					}).then(s => {
						if (s.code === 20000) {
							console.log('添加收藏', s);
							this.collectIds.push(this.currentQuestion.id)
							// this.getCollectionList();
							uni.showToast({
								title: '收藏成功',
								icon: 'none',
								duration: 1500
							});
						} else {
							uni.showToast({
								title: s.message,
								icon: 'none'
							})
						}
					})
				}
			},
			groupChange(n) {
				this.examList[this.currentNum - 1].stuAnswer = this.userAnswer.answer
			},
			checkboxChange(n) {
				this.examList[this.currentNum - 1].stuAnswer = n
			},
			//上一题，下一题
			preNextClick(p) {
				if (this.total === this.currentNum) { //examList.length
					//最后一题
					if (p == 1) { //下一题
						uni.showToast({
							title: '当前是最后一题',
							icon: 'none',
							duration: 1500
						})
					}
				} else if (this.examList.length === this.currentNum) {
					//请求下一页
					this.page++
					this.getWrongList()
				}
				this.currentNum = Math.max(1, Math.min(this.currentNum + p, this.total)) //examList.length
				this.checkAnswer()
			},
			getCurrentQuestion() {
				const data = _.cloneDeep(this.examList).find((_, i) => i === this.currentNum - 1) || {}
				data.options = Object.entries(data.options || {}).map(([key, value]) => ({
					label: key + "、" + value,
					value: key
				}))
				data.options = data.options
				this.$set(data, 'isShowAnswer', false) //添加一个新的字段
				// Object.assign(data,{isShowAnswer:false})
				return data
			},
			openAnswer() {
				// this.$forceUpdate()
			},
			closeAnswer() {
				this.showAnswerSheet = false
			},
			onAnswerSheet() {
				this.$forceUpdate()
				this.showAnswerSheet = !this.showAnswerSheet
			},
			onAnswerPanel(index) {
				this.currentNum = index + 1

			},
			outputList(list, source = 'default') {
				let outputStr = '';
				if (typeof list == 'string' || typeof list == 'number') return list;
				if (list != null)
					for (let i = 0; i < list.length; i++) {
						outputStr += list[i] + '';
					}
				return outputStr;
			},
			checkAnswer() {
				if (this.currentQuestion.type == 1 || this.currentQuestion.type == 2 || this.currentQuestion.type == 3) {
					if (this.currentQuestion.type == 1) {
						if (this.userAnswer.answer == [] || this.userAnswer.answer.length == 0) return;
						if (this.userAnswer.answer == this.currentQuestion.correctOptions) {
							this.isRightAnswer = true
							this.resultText = '回答正确'
							this.delWrongQue(this.currentQuestion.id)
						} else {
							this.isRightAnswer = false
							this.resultText = '回答错误'
						}
					}
					if (this.currentQuestion.type == 2) {
						if (this.userAnswer.answer == [] || this.userAnswer.answer.length == 0) return;
						if (typeof this.userAnswer.answer == 'object') {
							this.userAnswer.answer = this.userAnswer.answer.sort((a, b) => a.charCodeAt() - b
								.charCodeAt());
						}
						if (this.outputList(this.currentQuestion.correctOptions) != this.outputList(this.userAnswer
								.answer)) {
							if (this.userAnswer.answer == [] || this.userAnswer.answer.length == 0) return;
							this.isRightAnswer = false
							this.resultText = '回答错误'
						} else {
							this.isRightAnswer = true
							this.resultText = '回答正确'
							this.delWrongQue(this.currentQuestion.id)
						}
					}
					if (this.currentQuestion.type == 3) {
						if (this.userAnswer.answer == [] || this.userAnswer.answer.length == 0) return;
						if (this.userAnswer.answer == 1) {
							this.userAnswer.answer = 'A' //对
						} else {
							this.userAnswer.answer = 'B' //错
						}
						if (this.userAnswer.answer == this.currentQuestion.correctOptions) {
							this.isRightAnswer = true
							this.resultText = '回答正确'
							this.delWrongQue(this.currentQuestion.id)
						} else {
							this.isRightAnswer = false
							this.resultText = '回答错误'
						}
					}
				}
				// this.$forceUpdate()
			},
			onDetermine(val) {
				val.isShowAnswer = true
				this.checkAnswer()
				this.$forceUpdate()
			},
			getWrongList() {
				wrongMain({
					userId: this.userId,
					page: this.page,
					pageSize: this.pageSize
				}).then(s => {
					if (s.code === 20000) {
						if(this.examList.length==this.currentNum && this.currentNum != 1){//排除上一页1=1
							this.examList = this.examList.concat(s.data.question)
							
						}else{
							this.examList = s.data.question
						}
						this.total = s.data.total
						this.examList = this.examList.map(item => {
							return {
								...item,
								stuAnswer: '',
							}
						})
						// this.collectIds = this.examList.map(item => item.id)
					} else {
						uni.showToast({
							title: s.message,
							icon: 'none'
						})
					}
				})
			},
			//获取收藏列表
			getCollectionList() {
				topicCollectionList({
					userId: this.userId,
					page: this.page,
					pageSize: this.pageSize
				}).then(s => {
					if (s.code === 20000) {
						this.collectIds = s.data.records.map(item => item.questionId)
					} else {
						uni.showToast({
							title: s.message,
							icon: 'none'
						})
					}
				})
			},
			touchStart(event) { // 手指触摸屏幕时触发，有一个手指放在屏幕上也会触发
				this.startX = event.changedTouches[0].pageX // 触摸目标在页面中的X坐标
				// console.log('开始触摸：', this.startX);
			},
			touchEnd(event) { // 手指离开屏幕时触发
				// 获取滑动距离
				const moveX = event.changedTouches[0].pageX - this.startX
				// console.log("moveX", moveX);
				// 判断滑动方向
				if (moveX < -100 && this.currentNum <= this.examList.length) {
					// 【下一题】 判断大幅度左滑且不是最后一题
					if (this.examList.length === this.currentNum) {
						uni.showToast({
							title: '当前是最后一题',
							icon: 'none',
							duration: 1500
						})
					}
					this.preNextClick(1)
				} else if (moveX > 100 && this.currentNum != 0) {
					// 【上一题】 判断大幅度右滑且不是第一题
					this.preNextClick(-1)
				}
			},
			//删除单个错题
			delWrongQue(id) {
				delWrong({
					id: id,
				}).then(s => {
					if (s.code === 20000) {						
						this.preNextClick(-1)
						this.getWrongList()
						this.$forceUpdate()
					} else {
						uni.showToast({
							title: s.message,
							icon: 'none'
						})
					}
				})
			},
			//删除该用户的全部错题
			delWrongAll() {
				let that= this
				uni.showModal({
					title: '提示',
					content: '您确定要清空所有错题吗',
					success: function(res) {
						if (res.confirm) {
							delWrongAll({
								userId: that.userId,
							}).then(s => {
								if (s.code === 20000) {
									uni.showToast({
										title: s.message,
										icon: 'none',
										duration: 1500
									})
									that.preNextClick(-1)//上一题
									that.getWrongList()
									that.$forceUpdate()
								} else {
									uni.showToast({
										title: s.message,
										icon: 'none'
									})
								}
							})
						} else if (res.cancel) {
							console.log('用户点击取消');
						}
					}
				})
			},
		},
		watch: {
			userAnswer: {
				handler(old, news) {
					// console.log("watch userAnswer old,news", old, news);
				},
				deep: true
			},
			currentQuestion(value) { //题目信息
				if (value.type == 1) {
					if (value.stuAnswer.length > 0) {
						this.userAnswer.answer = value.stuAnswer
						// this.checkAnswer()
					} else {
						this.userAnswer.answer = ''
					}
				}
				if (value.type == 2) {
					if (value.stuAnswer.length > 0) {
						this.userAnswer.answer = value.stuAnswer
						// this.checkAnswer()
					} else {
						this.userAnswer.answer = []
					}
				}
				if (value.type == 3) {
					if (value.stuAnswer.length > 0) {
						this.userAnswer.answer = value.stuAnswer
						// this.checkAnswer()
					} else {
						this.userAnswer.answer = ''
					}
				}
			},
		},
		computed: {
			currentQuestion() {
				return this.getCurrentQuestion()
			},
			questionType() {
				return {
					1: '单选',
					2: '多选',
					3: '判断'
				} [this.currentQuestion.type]
			},
			getBackgroundColor() {
				return function(item = {}) {
					if (this.currentQuestion.type == 1) {
						if (this.currentQuestion.correctOptions == item.value && item.value == this.currentQuestion
							.stuAnswer) {
							return {
								backgroundColor: 'rgb(168 255 173)'
							};
						} else if (this.currentQuestion.correctOptions != item.value && item.value == this
							.currentQuestion
							.stuAnswer) {
							return {
								backgroundColor: '#ffbaba'
							};
						} else if (this.currentQuestion.correctOptions == item.value) {
							return {
								backgroundColor: 'rgb(168 255 173)'
							};
						} else return {};
					}
					if (this.currentQuestion.type == 3) {
						let YorN = ''
						if (item == 0) {
							YorN = 'B'
						} else {
							YorN = 'A'
						}
						if (this.currentQuestion.correctOptions[0] == YorN) {
							return {
								backgroundColor: 'rgb(168 255 173)'
							};
						} else if (this.currentQuestion.correctOptions[0] != YorN) {
							return {
								backgroundColor: '#ffbaba'
							};
						} else return {};
					}
				}
			},
			answerEqual() {
				return function(a, b, c) {
					if (c == 1) {
						return a === b[0];
						// return a[0] === b[0];
					} else if (typeof a === 'object' && typeof b === 'object') {
						return JSON.stringify(a) === JSON.stringify(b);
					}
					if (c == 3) {
						let YorN = ''
						if (a == 0) {
							YorN = 'B' //错
						} else {
							YorN = 'A' //对
						}
						return b[0] === YorN
					}
					return a === b;
				};
			},
		}
	}
</script>

<style lang="scss" scoped>
	.container {
		width: 100%;
		position: relative;
		background: #F2F2F2;
		height: calc(100vh - 44px);
	}

	.main_content {
		width: 100%;
		background: #fff;
		// transition: all 0.5s ease; 
		transform: translateX(0);
		transition: transform 0.5s ease;

		// height: 400rpx;
		.u-swiper {
			height: 800rpx;
		}

		.questTypeContent {
			height: 41px;
			line-height: 41px;
			padding: 0 14px;
			box-sizing: border-box;
			background: #fff;

			.questionType {
				height: 28px;
				line-height: 28px;
				font-size: 13px;
				color: #78A3FD;
				background: #EEF2FF;
				padding: 0rpx 15rpx;
				box-sizing: border-box;
				border-radius: 10rpx;
			}

			.questionAmount {
				font-size: 12px;
				color: #999;

				.activeClr {
					color: #3888FF;
					font-size: 14px;
				}
			}
		}

		.questionContent {
			padding: 14px;
			box-sizing: border-box;
			font-size: 34rpx;
			box-shadow: 4px 4px 10px #EEF2FF inset;

			.questionTitle {
				margin-bottom: 24rpx;
				line-height: 1.5;
			}

			.answer_item {
				margin-top: 20rpx;
			}
		}
	}

	.bottom_area {
		position: fixed;
		bottom: 0;
		left: 0;
		width: 100%;
		box-sizing: border-box;
		padding: 10rpx 30rpx;
		background: #fff;

		.collection {
			margin-right: 20rpx;
			text-align: center;

			image {
				width: 50rpx;
				height: 50rpx;

			}
		}

		.answerSheet {
			margin-right: 20rpx;
			text-align: center;

			image {
				width: 50rpx;
				height: 50rpx;

			}
		}

	}

	.answerPanel {
		transition: right 0.3s ease;
		z-index: 1001;
		background-color: white;
		box-shadow: 0 4px 16px 0 rgba(0, 0, 0, 0.1);
		padding: 40rpx;
		box-sizing: border-box;

		.card_title {
			font-weight: bold;
			color: #0d0e10;
			text-align: left;
			padding-left: 10px;
			font-size: 14px;
			border-left: #3888FF 3px solid;
			box-sizing: border-box;
		}

		.titleTxt {
			font-size: 12px;
			color: #9cb2cd;
			text-indent: 0;
			margin-left: 5px;
		}
	}

	.titleText {
		position: relative;
		display: inline-block;
		border: 1px solid #bfbfbf;
		width: 12px;
		height: 12px;
		text-indent: 0;
		margin-left: 3px;
		top: 2px;
	}

	.titleRight {
		background: green;
	}

	.titleError {
		background: red;
	}

	.card_content {
		padding: 20px 0 10px 0;
		box-sizing: border-box;
		overflow-y: auto;
		min-height: 260px;
		max-height: 400px;
	}

	.picker-item {
		cursor: pointer;
		width: 38px;
		height: 38px;
		line-height: 38px;
		text-align: center;
		border: 1px solid #dddddd;
		border-radius: 5px;
		background: #ffffff;
		-webkit-user-select: none;
		-moz-user-select: none;
		-ms-user-select: none;
		user-select: none;
		float: left;
		margin: 4px 6px;
		position: relative;
		overflow: hidden;

		// &.normal {
		// 	background: #3888FF;
		// 	color: #fff;
		// }
		&.error {
			background: red;
			color: #fff;
		}

		&.right {
			background: green;
			color: #fff;
		}
	}

	.answerResult {
		margin-top: 50rpx;
		color: #999;

		.answerIcon {
			margin-right: 20rpx;
		}

		.answers {
			margin-top: 30rpx;

			.answerTxt {
				margin-bottom: 15rpx;
			}
		}

	}

	.analysis {
		margin-top: 20rpx;
		width: 100%;
		background: #fff;
		padding: 14px;
		box-sizing: border-box;

		.analysisTitle {
			font-size: 16px;
			color: #666;
			line-height: 22px;
			font-weight: 700;

		}

		.analysisContent {
			white-space: pre-wrap;
			padding: 6px 0 12px;
			border-bottom: 1px dashed #ddd;
			margin-bottom: 11px;

		}
	}

	.determineBtn {
		width: 100%;
		padding-top: 60rpx;
		box-sizing: border-box;
		position: relative;

		.itemBtn {
			width: 30%;
			position: absolute;
			right: 0;
			top: 0;
		}
	}

	.delItem {
		width: 100%;
		padding-top: 60rpx;
		box-sizing: border-box;
		position: relative;

		.delBtn {
			width: 150rpx;
			height: 150rpx;
			border-radius: 50%;
			position: absolute;
			right: 30rpx;
			top: 200rpx;
		}
	}
</style>